<template>
  <div class="search">
    <van-nav-bar fixed title="商品列表" left-arrow @click-left="$router.go(-1)" />

    <van-search
      readonly
      shape="round"
      background="#ffffff"
      :value="querySearch || '搜索商品'"
      show-action
      @click="$router.push('/search')"
    >
      <template #action>
        <van-icon class="tool" name="apps-o" />
      </template>
    </van-search>

    <!-- 排序选项按钮 -->
    <div class="sort-btns">
      <div class="sort-item" @click="ranking('all')">综合</div>
      <div class="sort-item" @click="ranking('sales')">销量</div>
      <div class="sort-item" @click="ranking('prices',raise)">价格 </div>
    </div>

    <div class="goods-list">
      <GoodsItem v-for="item in proList" :key="item.goods_id" :item="item"></GoodsItem>
    </div>
  </div>
</template>

<script>
import GoodsItem from '@/components/GoodsItem.vue'
import { getProduct } from '@/api/product'
export default {
  name: 'SearchIndex',
  components: {
    GoodsItem
  },
  computed: {
    // 获取地址栏的搜索关键字
    querySearch () {
      return this.$route.query.search
    }
  },
  data () {
    return {
      // 页数
      page: 1,
      // 商品列表
      proList: [],
      raise: 1

    }
  },
  async created () {
    this.ranking()
    const { data: { list } } = await getProduct({
      // 传入商品id
      categoryId: this.$route.query.categoryId,
      // 传入商品名称
      goodsName: this.querySearch,
      // 商品页数
      page: this.page
    })
    this.proList = list.data
    // console.log(this.proList)
  },
  methods: {
    async ranking (key, raise) {
      const { data: { list } } = await getProduct({
        sortType: key,
        // 价格排序
        sortPrice: raise,
        // 传入商品id
        categoryId: this.$route.query.categoryId,
        // 传入商品名称
        goodsName: this.querySearch,
        // 商品页数
        page: this.page
      })
      // 重新渲染
      this.proList = list.data
      // console.log(this.proList)
      this.raise = this.raise === 1 ? 0 : 1
      // console.log(this.raise)
    }
  }
}

</script>

<style lang="less" scoped>
.search {
  padding-top: 46px;
  ::v-deep .van-icon-arrow-left {
    color: #333;
  }
  .tool {
    font-size: 24px;
    height: 40px;
    line-height: 40px;
  }

  .sort-btns {
    display: flex;
    height: 36px;
    line-height: 36px;
    .sort-item {
      text-align: center;
      flex: 1;
      font-size: 16px;
    }
  }
}

// 商品样式
.goods-list {
  background-color: #f6f6f6;
}
</style>
